package com.sir.tao.carhire.util;

import com.alibaba.fastjson.JSON;
import com.sir.tao.carhire.entity.table.AdministratorsEntity;
import com.sir.tao.carhire.shiro.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author dyy
 * @data 2021/12/23 22:18
 * @description:
 */
@Component
public class RedisUtil {


    @Resource
    private RedisTemplate<Object,String> redisTemplate;


    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }



    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     */
    public void expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doRedis(AdministratorsEntity administratorsEntity, String token) {
        set("prefix_user_entity_"+administratorsEntity.getUsername(), JSON.toJSONString(administratorsEntity));
        expire("prefix_user_entity_" + administratorsEntity.getUsername(), JwtUtil.EXPIRE_TIME *2 / 1000);
        set("prefix_user_token_" +administratorsEntity.getUsername(), token);
        expire("prefix_user_token_" + administratorsEntity.getUsername(), JwtUtil.EXPIRE_TIME *2 / 1000);
    }


}
